package com.linyifan.firstdemo.repository;

import com.linyifan.firstdemo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 仓储
 */
@Repository
public class UserRepository {

    /**
     * 使用map进行存储
     */
    private final ConcurrentMap<Integer,User> repository = new ConcurrentHashMap<>();

    private final static AtomicInteger idGenerator = new AtomicInteger();

    /**
     * 保存对象
     * @param user
     * @return 成功返回true
     */
    public boolean save(User user){
        //从1开始
        Integer id = idGenerator.incrementAndGet();
        user.setId(id);
        User put = repository.put(id, user);
        return put == null;
    }
}
